package net.zoneland.zrdp.framework.web.service.impl;

import com.branchitech.account.command.bean.ShowType;
import com.branchitech.account.command.util.CommandUtil;
import com.branchitech.account.ldap.Department;
import com.branchitech.account.ldap.UserBean;
import com.google.common.collect.ImmutableList;
import com.richercloud.lift.util.function.enhancer.BiFunctionEnhancer;
import net.zoneland.zrdp.framework.config.UomConfig;
import net.zoneland.zrdp.framework.web.domain.bean.DeptParam;
import net.zoneland.zrdp.framework.web.domain.bean.SearchPersonUserInfo;
import net.zoneland.zrdp.framework.web.domain.bean.UserParam;
import net.zoneland.zrdp.framework.web.domain.mapstruct.PeopleSelectConverter;
import net.zoneland.zrdp.framework.web.domain.vo.CompanyDepartmentVo;
import net.zoneland.zrdp.framework.web.domain.vo.SelectUserVo;
import net.zoneland.zrdp.framework.web.service.PeopleSelectService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.stream.Streams;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class PeopleSelectServiceImpl implements PeopleSelectService {

    /**
     * 登录账号 key
     */
    public static final String LOGIN_NAME = "loginName";

    /**
     * 登录密码 key
     */
    public static final String PWD = "pwd";

    /**
     * 搜索关键字 key
     */
    public static final String KEYWORD = "keyword";

    /**
     * 最大返回数量 key
     */
    public static final String MAX = "max";

    /**
     * 模糊查询人员信息
     */
    public static final String SEARCH_PERSONS = "searchPersons";

    /**
     * 人员选择框搜索默认最大返回条数
     */
    public static final int SEARCH_MAX_PAGE_SIZE = 30;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private UomConfig uomConfig;

    private static final List<CompanyDepartmentVo> ALL_COMPANY = ImmutableList.of(
        CompanyDepartmentVo.buildCompany("O=zmcc", "省公司"),
        CompanyDepartmentVo.buildCompany("OU=hzzmcc,O=zmcc","杭州分公司"),
        CompanyDepartmentVo.buildCompany("OU=huzmcc,O=zmcc", "湖州分公司"),
        CompanyDepartmentVo.buildCompany("OU=nbzmcc,O=zmcc", "宁波分公司"),
        CompanyDepartmentVo.buildCompany("OU=wzzmcc,O=zmcc", "温州分公司"),
        CompanyDepartmentVo.buildCompany("OU=sxzmcc,O=zmcc", "绍兴分公司"),
        CompanyDepartmentVo.buildCompany("OU=tzzmcc,O=zmcc", "台州分公司"),
        CompanyDepartmentVo.buildCompany("OU=jhzmcc,O=zmcc", "金华分公司"),
        CompanyDepartmentVo.buildCompany("OU=lszmcc,O=zmcc", "丽水分公司"),
        CompanyDepartmentVo.buildCompany("OU=qzzmcc,O=zmcc", "衢州分公司"),
        CompanyDepartmentVo.buildCompany("OU=zszmcc,O=zmcc", "舟山分公司"),
        CompanyDepartmentVo.buildCompany("OU=jxzmcc,O=zmcc", "嘉兴分公司")
    );

    @Override
    public List<CompanyDepartmentVo> queryDepartments(final DeptParam param) {
        final int level = param.getLevel();
        if (level == 1) {
            // 固定返回这些地市
            return ALL_COMPANY;
        }
        final String parentDn = param.getParentDn();
        if(StringUtils.isBlank(parentDn)){
            return Collections.emptyList();
        }
        final Department[] subDepts = CommandUtil.getSubDepts(parentDn, ShowType.SHOW, null, null);
        return Streams.of(subDepts)
            .map(BiFunctionEnhancer.of(PeopleSelectConverter.INSTANCE::departmentToCompanyDepartmentVo).partialRight(parentDn))
            .collect(Collectors.toList());
    }

    @Override
    public List<SelectUserVo> queryUsers(final UserParam userParam) {
        final String queryText = userParam.getQueryText();
        if(StringUtils.isNotBlank(queryText)){
            // 模糊查询人员信息
            return Streams.of(searchPerson(queryText, userParam.getMaxCount()))
                .map(PeopleSelectConverter.INSTANCE::searchPersonUserInfoToSelectUserVo)
                .collect(Collectors.toList());
        }
        final String parentDeptFullName = userParam.getParentDeptFullName();
        if(StringUtils.isBlank(parentDeptFullName)){
            return Collections.emptyList();
        }
        // 根据部门全称查询人员信息
        final UserBean[] userBeans = CommandUtil.getUsersByCompositor(parentDeptFullName);
        return Streams.of(userBeans)
            .map(BiFunctionEnhancer.of(PeopleSelectConverter.INSTANCE::userBeanToSelectUserVo).partialRight(parentDeptFullName))
            .collect(Collectors.toList());
    }

    private SearchPersonUserInfo[] searchPerson(final String keyword, final int maxCount) {
        final MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add(LOGIN_NAME, uomConfig.getLoginName());
        params.add(PWD, uomConfig.getLoginPwd());
        params.add(KEYWORD, keyword);
        params.add(MAX, String.valueOf(Math.max(maxCount, SEARCH_MAX_PAGE_SIZE)));
        return restTemplate.postForObject(uomConfig.getMemberServiceUrl() + SEARCH_PERSONS, params, SearchPersonUserInfo[].class);
    }
}
